package com.lnsoft.swidpdhclast.testlitepal;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Toast;

import net.sqlcipher.database.SQLiteDatabase;

import org.litepal.LitePal;

import java.io.File;
import java.util.List;


public class MainActivity extends AppCompatActivity  {

    //手机SD卡根目录
    private final String SDcardPath = "/mnt/sdcard/";

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Student student = new Student("onex99", "12", "man");
        student.save();
        Student student1 = new Student("onex18", "12", "man");
        student1.save();
        Student student2 = new Student("onex28", "12", "man");
        student2.save();
        Student student3 = new Student("jaima9", "12", "man");
        student3.save();


        findViewById(R.id.jm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                decrypt("ttt.db","dec2.db","onexzgj");


            }
        });

        requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},99);
        List<Student> all = LitePal.findAll(Student.class);
        Toast.makeText(this, all.size()+all.get(0).getName(), Toast.LENGTH_SHORT).show();
    }


    /**
     * @param encryptedName  加密数据库名称
     * @param decFile 解密后的数据库名称
     * @param key 加密使用的Key
     */
    //将加密的数据库文件数据写入到新的数据库文件中
    private void decrypt(String encryptedName,String decFile,String key) {
        try {
            File databaseFile = getDatabasePath(SDcardPath + encryptedName);
//            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, key, null);
//
//            File decrypteddatabaseFile = getDatabasePath(SDcardPath + decryptedName);
//            //deleteDatabase(SDcardPath + decryptedName);
//
//            //连接到解密后的数据库，并设置密码为空
//            database.rawExecSQL(String.format("ATTACH DATABASE '%s' as " + decryptedName.split("\\.")[0] + " KEY '';", decrypteddatabaseFile.getAbsolutePath()));
//            database.rawExecSQL("SELECT sqlcipher_export('" + decryptedName.split("\\.")[0] + "');");
//            database.rawExecSQL("DETACH DATABASE " + decryptedName.split("\\.")[0] + ";");
//
//            SQLiteDatabase decrypteddatabase = SQLiteDatabase.openOrCreateDatabase(decrypteddatabaseFile, "", null);
//            //decrypteddatabase.setVersion(database.getVersion());
//            decrypteddatabase.close();
//
//            database.close();


            File decrypteddatabaseFile = getDatabasePath(SDcardPath + decFile);
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, key, null);

            if (database.isOpen()) {
                database.rawExecSQL(String.format("ATTACH DATABASE '%s' as plaintext KEY '';", decrypteddatabaseFile.getAbsolutePath()));
                database.rawExecSQL("SELECT sqlcipher_export('plaintext');");
                database.rawExecSQL("DETACH DATABASE plaintext;");
                SQLiteDatabase sqlDB = SQLiteDatabase.openDatabase(decFile,"",null,0);

                sqlDB.close();
                database.close();
            }






        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    public void requestPermissions(int requestCode, String permission) {
        if (permission != null && permission.length() > 0) {
            try {
                if (Build.VERSION.SDK_INT >= 23) {
                    // 检查是否有权限
                    int hasPer = checkSelfPermission(permission);
                    if (hasPer != PackageManager.PERMISSION_GRANTED) {
                        // 是否应该显示权限请求
                        boolean isShould = shouldShowRequestPermissionRationale(permission);
                        requestPermissions(new String[]{permission}, requestCode);
                    }else {

                    }
                } else {

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
        if (!flag) {
            requestPermissions(99, Manifest.permission.CAMERA);
        }
    }

}
